<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\impl;

use lflow\core\Execution;
use lflow\lib\interface\WorkFlowInterceptor;
use lflow\lib\util\Logger;
use lflow\lib\util\StringHelper;

/**
 * 委托代理拦截器
 * 负责查询wf_surrogate表获取委托代理人，并通过addTaskActor设置为参与者
 * 这里是对新创建的任务通过添加参与者进行委托代理(即授权人、代理人都可处理任务)
 * 对于运行中且未处理的待办任务，可调用engine.task().addTaskActor方法
 * {@link ITaskService#addTaskActor(String, String...)}
 *
 * @author Mr.April
 * @since  1.0
 */
class SurrogateInterceptor implements WorkFlowInterceptor
{

    public function intercept(Execution $execution): void
    {
        $engine = $execution->getEngine();
        foreach ($execution->getTasks() as $task) {
            if (empty($task->getData('actor_ids'))) continue;
            foreach ($task->getData('actor_ids') as $actor) {
                if (empty($actor)) continue;
                $agent = $engine->manager()->getSurrogates($actor, $execution->getProcess()->getData('id'));
                //操作人跟代理人不相同添加任务处理人
                if (StringHelper:: isNotEmpty($agent) && !StringHelper::equalsIgnoreCase($agent, $actor)) {
                    //添加任务处理人
                    Logger::error('任务代理'.$task->getData('id'));
                    $engine->task()->addTaskActor($task->getData('id'),null, $agent);
                }
            }
        }
    }
}
